import Show from 'common/show.js'
import {
	apiBaseURL
} from './config.js';

// 异步请求
function request(url, method, data, header = {}) {
	// 自动将accessToken添加到request的header中
	header.token = uni.getStorageSync('token') ? uni.getStorageSync('token') : '';
	// #ifdef MP-WEIXIN
	header.source = 'web'
	// #endif
	// #ifdef APP-PLUS
	header.source = 'app'	
	// #endif
	return new Promise((resolve, reject) => {
		uni.request({
			url: apiBaseURL + url,
			data: data,
			header: header,
			method: method,
			responseType:'blob',
			success: (res) => {
				console.log('记录url:'+url+"请求:"+JSON.stringify(data)+",返回: "+JSON.stringify(res));
				
				if(url == '/unifiedPay/unifiedPay'){
					resolve(res)
					return
				}
				if (res.data.responseCode == '0000000') { // 成功
					resolve(res.data.data);
				} else if (res.data.responseCode == '200003') { //非法请求或者token过期
					// Show.show(res.data.responseMsg);
					// setTimeout(()=>{
					// 	uni.reLaunch({
					// 		url:'/pages/login/index'
					// 	})
					// },1500)
					uni.reLaunch({
						url: '/pages/login/index'
					})
				} else { // 失败
				   if(url == '/deleteFamilyMemberById' || url == '/acceptInvite' ){
					   reject(res.data.responseMsg)
				   }else{
					   Show.show(res.data.responseMsg);
				   }
					return
				}
			},
			fail: (error) => {
				if (error.statusCode !== 200) {
					showError(error.statusCode)
					return
				}
			},
			complete: () => {
				setTimeout(function() {
					uni.hideLoading();
				}, 1500);
			}
		})
	})
}

//get
export const get = (url, data) => {
	return request(url, 'get', data, {
		'content-type': 'application/json'
	});
}

//post
export const post = (url, data) => {
	let query = data ? data : {}
	query.base = {
		requestId: Math.floor(Math.random() * 1000000000) + '',
		clientId: 'minghui',
		debugMode: false
	}
	return request(url, 'post', query, {
		'content-type': 'application/x-www-form-urlencoded'
	});
}

//postJson
export const postJson = (url, data) => {
	let query = data ? data : {}
	query.base = {
		requestId: Math.floor(Math.random() * 1000000000) + '',
		clientId: 'minghui',
		debugMode: false
	}
	return request(url, 'post', query, {
		'content-type': 'application/json'
	});
}

const showError = code => {
	let errorMsg = ''
	switch (code) {
		case 400:
			errorMsg = '请求参数错误'
			break
		case 401:
			errorMsg = '未授权，请登录'
			break
		case 403:
			errorMsg = '跨域拒绝访问'
			break
		case 404:
			errorMsg = `请求地址出错: ${apiBaseURL}`
			break
		case 408:
			errorMsg = '请求超时'
			break
		case 500:
			errorMsg = '服务器内部错误'
			break
		case 501:
			errorMsg = '服务未实现'
			break
		case 502:
			errorMsg = '网关错误'
			break
		case 503:
			errorMsg = '服务不可用'
			break
		case 504:
			errorMsg = '网关超时'
			break
		case 505:
			errorMsg = 'HTTP版本不受支持'
			break
		default:
			errorMsg = '网络异常'
			break
	}

	uni.showToast({
		title: errorMsg,
		icon: 'none',
		complete: function() {
			setTimeout(function() {
				uni.hideToast();
			}, 1500);
		}
	});
}